#import evtx
#from evtx import PyEvtxParser
from tinydb import TinyDB, Query
import datetime,os
import webbrowser
from fastapi import FastAPI
import uvicorn
from starlette.responses import HTMLResponse
webbrowser.open("http://127.0.0.1:8000/search")
print('hello')
#today=str(datetime.datetime.today())[:10]

if os.path.exists('database'):
    pass
else:
    os.mkdir('database')
#db = TinyDB('database/'+today+'.json')

#for item in list0:
#    db.insert({'name': item})
#User = Query()

#print(db.search(User.name.test(test_func))[10:20])
#db.close()
print('end')
html_head='''
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    
    <title>log analysis system</title>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
  </head>
'''
html_body_start='''
  <body>
    <h1 align="center">日志<a href="/evtxlist">evtx</a>查询分析系统</h1>

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
'''
form0='''
<form class="form-inline action="?" method="get" style="text-align:center;vertical-align:middle;">
  <div class="form-group">
    <label for="exampleInputName2">请先选择日期再输入要检索的内容:</label>
    <input type="date" value={} name="selecttime"/>
    <input type="text" class="form-control" id="exampleInputName2" placeholder="关键词" name="q">
  </div>

  <button type="submit" class="btn btn-default">搜索</button>
</form>
'''
evtxlist='''
'''

app = FastAPI()
@app.get("/search")

def search(q: str = None,selecttime: str = None,page:int=1):
    today=str(datetime.datetime.today())[:10]
    if selecttime is None:
        selecttime=today
    if q:

        
        z=html_head+html_body_start+form0+q
        #db = TinyDB('database/'+today+'.json')
        db = TinyDB('database/'+selecttime+'.json')
        User = Query()
        test_func = lambda s:  q in s
        list0=db.search(User.name.test(test_func))
        #print(list0)
        len0=len(list0)
        step=10
        pages_num=(len0//step)+1
        print('start2',len(list0))

        #list0=[]
        #for i in range(12):
        #    list0.append(str(i))
        
        start=(page-1)*step
        end=page*step
        list1=list0[start:end]
        content=''
        for item in list1:
            content=content+item['name'].replace('<','&lt;').replace('>','&gt;').replace('   ','<br>').replace('EventID','<font size="3" color="blue">EventID</font>')\
                     .replace('IpAddress','<font size="3" color="blue">IpAddress</font>').replace('SystemTime','<font size="3" color="blue">SystemTime</font>')\
                     .replace('TargetUserName','<font size="3" color="blue">TargetUserName</font>').replace(q,'<font size="3" color="red">{}</font>'.format(q))+'<HR color=#987cb9 SIZE=1>'
            #content=content+item['name'].replace(q,'<font size="3" color="red">{}</font>'.format(q))+'<HR color=#987cb9 SIZE=3>'
        #pagex='<li><a href="?q={}&page={}">{}</a></li>'.format(q,page,page)
        #无网络版分页标签
        pagination='<div>'+' '.join(list(map(lambda x:'<a style="display: inline-block;white-space:nowrap" href="?q={}&selecttime={}&page={}">{}</a>'.format(q,selecttime,x,x),range(1,pages_num+1))))+'</div>'

        #bootstrap版分页标签
        #pagination='<ul class="pagination pagination-sm">'+\
        #            ' '.join(list(map(lambda x:'<li><a style="display: inline-block;white-space:nowrap" href="?q={}&selecttime={}&page={}">{}</a></li>'.format(q,selecttime,x,x),range(1,pages_num+1))))+'</ul><br>'
        pages='<ul class="pagination"><li><a href="#">1</a></li><li><a href="#">2</a></li></ul>'
        z=html_head+html_body_start+form0.format(selecttime)+pagination+content
        db.close()
    else:
        

        #for item in list0:
        #    db.insert({'name': item})
        z=html_head+html_body_start+form0.format(selecttime)
    return HTMLResponse(content=z)
@app.get("/evtxlist")
def evtslist1():
    return HTMLResponse(content=evtxlist)
if __name__ == "__main__":

    uvicorn.run(app, host="127.0.0.1",port=8000,log_level="info")
